package com.qiaofang.applet.exception.handler;

import com.qiaofang.applet.common.dto.DataResponse;
import com.qiaofang.applet.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 全局异常处理类
 * @author QF2019
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.qiaofang.applet")
public class GlobalExceptionHandler {

    private static final String ERROR_MSG = "系统繁忙,请稍后再试";

    /**
     * 处理所有不可知的异常
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public DataResponse<Object> handleException(HttpServletRequest request, Throwable ex){
        log.error("未知异常,url:{}", request.getRequestURL(), ex);
        return DataResponse.fail(ERROR_MSG);
    }

    /**
     * 参数校验失败处理方法
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public DataResponse<Object> handleMethodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException ex) {
        log.error("参数异常,url:{}", request.getRequestURL(), ex);
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        StringBuilder str = new StringBuilder("参数校验失败！原因[");
        for(FieldError fieldError : fieldErrors){
            str.append("{").append(fieldError.getField()).append(":")
                    .append(fieldError.getDefaultMessage()).append("}");
        }
        str.append("]");
        log.error("参数校验失败，url:{}, msg:{}",request.getRequestURI(), str);
        return DataResponse.fail(str.toString());
    }

    /**
     * 业务显式抛出的异常处理方法
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public DataResponse<Object> handleServiceException(HttpServletRequest request, BusinessException ex) {
        log.error("BusinessException，url:{}",request.getRequestURI(), ex);
        return DataResponse.fail(ex.getMessage());
    }
}
